﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Threading.Tasks;
using System;
using TyMES.Model.BaseInformation;
using WalkingTec.Mvvm.Core;
using System.Linq;
using TyMES.Communication;
using TyMES.TemporaryClass;

namespace TyMES.Services
{
    public class TrayService
    {
        private readonly ILogger logger;
        private readonly IConfiguration configuration;
        private readonly HttpService httpService;
        private readonly IServiceScope serviceScope;
        private readonly WTMContext context;

        public TrayService(ILogger<TrayService> logger, IConfiguration configuration, HttpService httpService, IServiceScopeFactory serviceScopeFactory)
        {
            this.logger = logger;
            this.configuration = configuration;
            this.httpService = httpService;
            this.serviceScope = serviceScopeFactory.CreateScope();
            var sp = this.serviceScope.ServiceProvider;
            this.context = sp.GetRequiredService<WTMContext>();
        }

        // 增加托盘使用次数
        public async Task<ResponseBase> AddUsedNumAsync(string trayCode)
        {
            try
            {
                Tray tray = context.DC.Set<Tray>().SingleOrDefault(e => e.TrayCode == trayCode);
                if (tray == null)
                {
                    return new ResponseBase(false, "托盘编码错误，请上传正确的托盘编码");
                }
                tray.UsedTimes++;

                // 预警
                /*
                if(tray.UsedTimes > tray.PlannedTimes * 0.9)
                {
                    tray.TrayStation = "报废";
                }
                */
                await context.DC.SaveChangesAsync();
                return new ResponseBase(true, "更新成功");
            }
            catch (Exception ex)
            {
                return new ResponseBase(false, ex.Message);
            }
        }


        // 请求工厂MES获取虚拟SN
        public async Task<ResponseBase> Request4VirtualSNAsync(ParaTrayVSNInfo para)
        {
            //预先判断虚拟SN预存数量
            //有预存直接返回  目前默认无预存
            string factoryCode = configuration["FactoryCode"];
            string mesIP = configuration["MESIP"];
            string mesPort = configuration["MESPORT"];
            string url = "http://" + mesIP + ":" + mesPort + configuration["BASEURL"];

            ResquestBody4VirtualSN resquestBody = new ResquestBody4VirtualSN
            {
                factoryCode = factoryCode,
                serviceId = "Product001_SNCreate",
                requestTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                data = new List<TSdata>()
            };
            TSdata tsdata = new TSdata();
            tsdata.lineCode = para.lineCode;
            tsdata.orderCode = para.orderCode;
            tsdata.scheduleCode = para.scheduleCode;
            tsdata.barcodeCategory = para.barcodeCategory;
            tsdata.snQty = para.snQty;
            tsdata.stationCode = para.stationCode;
            resquestBody.data.Add(tsdata);

            try
            {
                string psd = JsonConvert.SerializeObject(resquestBody);

                logger.LogInformation(psd);
                string value = await httpService.PostDataAsync(url, psd);
                logger.LogInformation(value);

                VSNRes vsnres = new VSNRes();
                vsnres.data = new List<VSNdata>();
                vsnres = JsonConvert.DeserializeObject<VSNRes>(value);
                if (vsnres != null && vsnres.code == "000000")
                {
                    if (vsnres.data.Count > 0)
                    {
                        // 目前默认工厂MES只下发单个SN,下发多个后需增加存储功能，
                        // 先判断预存数量，没有预存调用工厂MES获取虚拟SN
                        return new ResponseBase(true, vsnres.data[0].snBarcode);
                    }
                }
                return new ResponseBase(false, vsnres.mesg);
            }
            catch (Exception ex)
            {
                return new ResponseBase(false, ex.Message);
            }
        }


        // 更新托盘和虚拟SN绑定关系
        public async Task<bool> UpdateRelationShipAsync(string trayCode, string virtualSN)
        {
            try
            {
                TrayBinding bind = context.DC.Set<TrayBinding>().SingleOrDefault(e => e.TrayCode == trayCode);
                if (bind != null)
                {
                    //插入
                    if (bind.VirtualSN != virtualSN)
                    {
                        bind.VirtualSN = virtualSN;
                    }
                    if (bind.IsValid == false)
                    {
                        bind.IsValid = true;
                    }
                }
                else
                {
                    bind = new TrayBinding()
                    {
                        TrayCode = trayCode,
                        VirtualSN = virtualSN,
                        IsValid = true
                    };
                    context.DC.Set<TrayBinding>().Add(bind);

                    //同时添加绑定记录
                }
                await context.DC.SaveChangesAsync();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }


        // 根据虚拟SN获取托盘信息  
        public ResponseBase FindRealtionship(string trayCode)
        {
            try
            {
                TrayBinding bind = context.DC.Set<TrayBinding>().SingleOrDefault(e => e.TrayCode == trayCode);
                if (bind == null)
                {
                    return new ResponseBase(false, "上传托盘码错误");
                }
                else if (bind.IsValid == false)
                {
                    return new ResponseBase(false, "该托盘无绑定信息");
                }
                else
                {
                    return new ResponseBase(true, bind.VirtualSN);
                }
            }
            catch (Exception ex)
            {
                return new ResponseBase(false, ex.Message);
            }

        }


        /*
        // 处理上料接口逻辑
        public ResponseBase LoadMaterial(string snNumber)
        {
            if(snNumber.Contains("S:"))
            {

            }
            else
            {
                return new ResponseBase() { Success = false, Mesg = "false" };
            }

        }
        */
    }
}